/*
 *  Copyright 2013 National Institute of Advanced Industrial Science and Technology
 *  
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.sss.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sss.mapreduce.SssException;

public class TaskSliceSubmitter<T> implements DataReceiver<T> {
  private static Logger logger = LoggerFactory.getLogger(TaskSliceSubmitter.class);
  private SentinelThreadPool pool;
  private InputDrivenTask<T> task;
  private SentinelThreadPool.TaskGroup group = new SentinelThreadPool.TaskGroup();
  private Throwable exception = null;

  public TaskSliceSubmitter(SentinelThreadPool pool, 
                            InputDrivenTask<T> task) {
    this.pool = pool;
    this.task = task;
  }

  @Override
  public void put(T bucket) throws SssException {
    checkAlreadyError();
    pool.execute(group, new TaskSlice(bucket));
  }

  @Override
  public void close() throws SssException {
    checkAlreadyError();
    pool.executeSentinel(group, new NoMoreTask());
  }

  @Override
  public void setError(Throwable e) {
    if (setException(e)) {
      pool.execute(group, new NoMoreTask());
    }
  }

  @Override
  public synchronized Throwable getError() {
    return exception;
  }

  private synchronized void checkAlreadyError() throws ErrorDataReceiverException {
    if (exception != null) {
      throw new ErrorDataReceiverException(exception);
    }
  }

  private synchronized boolean setException(Throwable e) {
    assert e != null;
    if (exception == null) {
      exception = e;
      return true;
    }
    else {
      if (!(exception instanceof ErrorDataReceiverException)) {
        logger.debug("Ignores this error because another error already has set.", e);
      }
      return false;
    }
  }

  private class TaskSlice implements Runnable {
    private final T bucket;

    public TaskSlice(T bucket) {
      this.bucket = bucket;
    }

    @Override
    public void run() {
      try {
        checkAlreadyError();
        task.handle(bucket);
      }
      catch (Throwable e) {
        if (setException(e)) {
          task.noMoreTaskSlice(e);
        }
      }
    }
  }

  private class NoMoreTask implements Runnable {
    @Override
    public void run() {
      try {
        task.noMoreTaskSlice(getError());
      }
      catch (Throwable e) {
        logger.error("Unexpected Exception: {}", e);
        throw new RuntimeException(e);
      }
    }
  }
}
